from tkinter import *
import tkinter.messagebox
from tkinter import ttk
from tkinter import font
from src.backend.employee_b import EmployeeBackend

class EmployeeFrontend:
    """Frontend UI for employee management"""
    
    def __init__(self, master, user_type='admin'):
        self.master = master
        self.user_type = user_type
        self.backend = EmployeeBackend()
        
        self.master.title("HOSPITAL MANAGEMENT SYSTEM")
        self.master.geometry("1500x700+0+0")
        self.master.config(bg="#C0C0C0")
        self.frame = Frame(self.master, bg="#C0C0C0")
        self.frame.pack()

        #=============ATTRIBUTES===========
        self.emp_ID = StringVar()
        self.emp_first_name = StringVar()
        self.emp_last_name = StringVar()
        self.emp_email = StringVar()
        self.emp_phone = StringVar()
        self.emp_specialization = StringVar()
        self.emp_dept_id = IntVar()
        self.emp_salary = StringVar()
        self.emp_license_number = StringVar()

        self.create_ui()

    def create_ui(self):
        """Create the user interface"""
        #===============TITLE==========
        self.lblTitle = Label(self.frame, text="EMPLOYEE REGISTRATION FORM", font="Arial 16 bold", bg="#C0C0C0", fg="#000080")
        self.lblTitle.grid(row=0, column=0, columnspan=2, pady=50)
        
        #==============FRAME==========
        self.LoginFrame = Frame(self.frame, width=400, height=80, relief="ridge", bg="#C0C0C0", bd=20)
        self.LoginFrame.grid(row=1, column=0)
        
        self.LoginFrame2 = Frame(self.frame, width=400, height=80, relief="ridge", bg="#C0C0C0", bd=20)
        self.LoginFrame2.grid(row=2, column=0)
        
        self.create_form_fields()
        self.create_buttons()

    def create_form_fields(self):
        """Create form input fields"""
        #===========LABELS=============          
        self.lblempid = Label(self.LoginFrame, text="EMPLOYEE ID", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblempid.grid(row=0, column=0)
        self.lblempid = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.emp_ID)
        self.lblempid.grid(row=0, column=1)
        
        self.lblempfirst = Label(self.LoginFrame, text="FIRST NAME", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblempfirst.grid(row=1, column=0)
        self.lblempfirst = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.emp_first_name)
        self.lblempfirst.grid(row=1, column=1)

        self.lblemplast = Label(self.LoginFrame, text="LAST NAME", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblemplast.grid(row=2, column=0)
        self.lblemplast = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.emp_last_name)
        self.lblemplast.grid(row=2, column=1)
        
        self.lblemail = Label(self.LoginFrame, text="EMAIL", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblemail.grid(row=3, column=0)
        self.lblemail = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.emp_email)
        self.lblemail.grid(row=3, column=1)
        
        self.lblphone = Label(self.LoginFrame, text="PHONE", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblphone.grid(row=4, column=0)
        self.lblphone = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.emp_phone)
        self.lblphone.grid(row=4, column=1)

        self.lblCon = Label(self.LoginFrame, text="SALARY", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblCon.grid(row=0, column=2)
        self.lblCon = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.emp_salary)
        self.lblCon.grid(row=0, column=3)
        
        self.lblspecialization = Label(self.LoginFrame, text="SPECIALIZATION", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblspecialization.grid(row=1, column=2)
        self.lblspecialization = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.emp_specialization)
        self.lblspecialization.grid(row=1, column=3)
        
        self.lbldept = Label(self.LoginFrame, text="DEPARTMENT ID", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lbldept.grid(row=2, column=2)
        self.lbldept = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.emp_dept_id)
        self.lbldept.grid(row=2, column=3)
        
        self.lblicense = Label(self.LoginFrame, text="LICENSE NUMBER", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblicense.grid(row=3, column=2)
        self.lblicense = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.emp_license_number)
        self.lblicense.grid(row=3, column=3)

    def create_buttons(self):
        """Create action buttons"""
        self.button2 = Button(self.LoginFrame2, text="SAVE", width=10, font="Arial 11 bold", bg="#C0C0C0", relief="raised", bd=2, command=self.INSERT_EMP)
        self.button2.grid(row=3, column=1, padx=5, pady=5)
        
        self.button3 = Button(self.LoginFrame2, text="DELETE", width=10, font="Arial 11 bold", bg="#C0C0C0", relief="raised", bd=2, command=self.DE_DISPLAY)
        self.button3.grid(row=3, column=2, padx=5, pady=5)
     
        self.button6 = Button(self.LoginFrame2, text="EXIT", width=10, font="Arial 11 bold", bg="#C0C0C0", relief="raised", bd=2, command=self.Exit)
        self.button6.grid(row=3, column=3, padx=5, pady=5)
        
        if self.user_type == 'root':
            self.btn_global = Button(self.LoginFrame2, text="GLOBAL SEARCH", width=15, font="Arial 11 bold", bg="#C0C0C0", relief="raised", bd=2, command=self.GLOBAL_EMP)
            self.btn_global.grid(row=4, column=1, columnspan=2, pady=10)
        
   #FUNCTION TO EXIT EMPLOYEE FORM
    def Exit(self):            
        self.master.destroy()
        
    #FUNCTION TO INSERT DATA IN EMPLOYEE FORM
    def INSERT_EMP(self):
        try:
            # Validate and process phone number
            phone = self.emp_phone.get().strip()
            phone_digits = ''.join(c for c in phone if c.isdigit())
            if len(phone_digits) < 7:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Phone number must have at least 7 digits")
                return
            
            # Get form data - store only digits for phone to fit VARCHAR(15)
            employee_data = {
                'staff_id': self.emp_ID.get().strip(),
                'first_name': self.emp_first_name.get().strip(),
                'last_name': self.emp_last_name.get().strip(),
                'email': self.emp_email.get().strip(),
                'phone': phone_digits,  # Store only digits
                'specialization': self.emp_specialization.get().strip(),
                'dept_id': self.emp_dept_id.get(),
                'salary': self.emp_salary.get().strip(),
                'license_number': self.emp_license_number.get().strip()
            }
            
            # Validate data
            is_valid, message = self.backend.validate_employee_data(employee_data)
            if not is_valid:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", message)
                return
            
            # Add employee to database
            if self.backend.add_employee(employee_data):
                tkinter.messagebox.showinfo("HOSPITAL DATABASE SYSTEM", "Employee added successfully")
                self.clear_form()
            else:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Failed to add employee")
                
        except Exception as e:
            tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", f"Error: {str(e)}")
    
    def clear_form(self):
        """Clear all form fields"""
        self.emp_ID.set("")
        self.emp_first_name.set("")
        self.emp_last_name.set("")
        self.emp_email.set("")
        self.emp_phone.set("")
        self.emp_specialization.set("")
        self.emp_dept_id.set(0)
        self.emp_salary.set("")
        self.emp_license_number.set("")
                
    #FUNCTION TO OPEN DELETE EMPLOYEE DISPLAY WINDOW
    def DE_DISPLAY(self):
        self.newWindow = Toplevel(self.master)
        self.app = D_EMP(self.newWindow, self.backend)

    def GLOBAL_EMP(self):
        """Open global employee search window with full CRUD functionality"""
        self.newWindow = Toplevel(self.master)
        self.app = GlobalEmployeeSearchMenu(self.newWindow, self.backend)

#CLASS FOR DISPLAY MENU FOR DELETE EMPLOYEE
class D_EMP:
    def __init__(self, master, backend):    
        self.master = master
        self.backend = backend
        self.master.title("HOSPITAL MANAGEMENT SYSTEM")
        self.master.geometry("1500x700+0+0")
        self.master.config(bg="#C0C0C0")
        self.frame = Frame(self.master, bg="#C0C0C0")
        self.frame.pack()
        self.de1_emp = StringVar()
        self.lblTitle = Label(self.frame, text="DELETE EMPLOYEE WINDOW", font="Arial 16 bold", bg="#C0C0C0", fg="#000080")
        self.lblTitle.grid(row=0, column=0, columnspan=2, pady=50)
        #==============FRAME==========
        self.LoginFrame = Frame(self.frame, width=400, height=80, relief="ridge", bg="#C0C0C0", bd=20)
        self.LoginFrame.grid(row=1, column=0)
        self.LoginFrame2 = Frame(self.frame, width=400, height=80, relief="ridge", bg="#C0C0C0", bd=20)
        self.LoginFrame2.grid(row=2, column=0)
        #===========LABELS=============          
        self.lblpatid = Label(self.LoginFrame, text="ENTER EMPLOYEE ID TO DELETE", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblpatid.grid(row=0, column=0)
        self.lblpatid = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.de1_emp)
        self.lblpatid.grid(row=0, column=1)

        self.DeleteB = Button(self.LoginFrame2, text="DELETE", width=10, font="Arial 11 bold", bg="#C0C0C0", relief="raised", bd=2, command=self.DELETE_EMP)
        self.DeleteB.grid(row=3, column=1, padx=5, pady=5)
        
    #FUNCTION TO DELETE DATA IN EMPLOYEE FORM 
    def DELETE_EMP(self):        
        try:
            staff_id = self.de1_emp.get().strip()
            if not staff_id:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Please enter Employee ID to delete")
                return
            
            # Check if employee exists
            employee = self.backend.get_employee(staff_id)
            if not employee:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Employee record not found")
                return
            
            # Confirm deletion
            result = tkinter.messagebox.askyesno("HOSPITAL DATABASE SYSTEM", 
                                               f"Are you sure you want to delete employee {employee[1]} {employee[2]}?")
            if result:
                if self.backend.delete_employee(staff_id):
                    tkinter.messagebox.showinfo("HOSPITAL DATABASE SYSTEM", "Employee deleted successfully")
                    self.de1_emp.set("")
                else:
                    tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Failed to delete employee")
        except Exception as e:
            tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", f"Error: {str(e)}")

#CLASS FOR GLOBAL EMPLOYEE SEARCH MENU (ROOT ONLY)
class GlobalEmployeeSearchMenu:
    def __init__(self, master, backend):    
        self.master = master
        self.backend = backend
        self.master.title("GLOBAL SEARCH - ALL EMPLOYEES")
        self.master.geometry("1200x600+0+0")
        self.master.config(bg="#C0C0C0")
        self.frame = Frame(self.master, bg="#C0C0C0")
        self.frame.pack()
        
        self.lblTitle = Label(self.frame, text="GLOBAL EMPLOYEE SEARCH", font="Arial 16 bold", bg="#C0C0C0", fg="#000080")
        self.lblTitle.grid(row=0, column=0, columnspan=2, pady=25)
        
        # Create Treeview for displaying all employees
        self.tree_frame = Frame(self.frame, bg="#C0C0C0")
        self.tree_frame.grid(row=1, column=0, padx=20, pady=10)
        
        # Define columns
        columns = ('ID', 'First Name', 'Last Name', 'Email', 'Phone', 'Specialization', 'Dept ID', 'Salary', 'License')
        self.tree = ttk.Treeview(self.tree_frame, columns=columns, show='headings', height=15)
        
        # Define headings
        for col in columns:
            self.tree.heading(col, text=col)
            self.tree.column(col, width=120)
        
        # Add scrollbar
        scrollbar = ttk.Scrollbar(self.tree_frame, orient=VERTICAL, command=self.tree.yview)
        self.tree.configure(yscrollcommand=scrollbar.set)
        
        # Pack treeview and scrollbar
        self.tree.pack(side=LEFT, fill=BOTH, expand=True)
        scrollbar.pack(side=RIGHT, fill=Y)
        
        # Buttons frame
        self.button_frame = Frame(self.frame, bg="#C0C0C0")
        self.button_frame.grid(row=2, column=0, pady=10)
        
        self.refresh_btn = Button(self.button_frame, text="REFRESH", width=15, font="Arial 11 bold", 
                                bg="#C0C0C0", relief="raised", bd=2, command=self.refresh_data)
        self.refresh_btn.pack(side=LEFT, padx=5)
        
        self.edit_btn = Button(self.button_frame, text="EDIT SELECTED", width=15, font="Arial 11 bold", 
                              bg="#C0C0C0", relief="raised", bd=2, command=self.edit_selected)
        self.edit_btn.pack(side=LEFT, padx=5)
        
        self.delete_btn = Button(self.button_frame, text="DELETE SELECTED", width=15, font="Arial 11 bold", 
                                bg="#C0C0C0", relief="raised", bd=2, command=self.delete_selected)
        self.delete_btn.pack(side=LEFT, padx=5)
        
        self.close_btn = Button(self.button_frame, text="CLOSE", width=15, font="Arial 11 bold", 
                               bg="#C0C0C0", relief="raised", bd=2, command=self.close_window)
        self.close_btn.pack(side=LEFT, padx=5)
        
        # Load initial data
        self.refresh_data()
    
    def refresh_data(self):
        """Refresh the employee data in the treeview"""
        try:
            # Clear existing data
            for item in self.tree.get_children():
                self.tree.delete(item)
            
            # Get all employees from database
            employees = self.backend.get_all_employees()
            
            # Insert data into treeview
            for employee in employees:
                self.tree.insert('', 'end', values=(
                    employee[0],  # ID
                    employee[1],  # First Name
                    employee[2],  # Last Name
                    employee[3],  # Email
                    employee[4],  # Phone
                    employee[5],  # Specialization
                    employee[6],  # Dept ID
                    employee[8],  # Salary
                    employee[7] or "N/A"  # License
                ))
                
        except Exception as e:
            tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", f"Error loading data: {str(e)}")
    
    def edit_selected(self):
        """Edit the selected employee"""
        selection = self.tree.selection()
        if not selection:
            tkinter.messagebox.showwarning("HOSPITAL DATABASE SYSTEM", "Please select an employee to edit")
            return
        
        # Get selected employee data
        item = self.tree.item(selection[0])
        staff_id = item['values'][0]
        
        # Open edit window
        self.edit_window = Toplevel(self.master)
        self.edit_app = EditEmployeeWindow(self.edit_window, staff_id, self.backend, self.refresh_data)
    
    def delete_selected(self):
        """Delete the selected employee"""
        selection = self.tree.selection()
        if not selection:
            tkinter.messagebox.showwarning("HOSPITAL DATABASE SYSTEM", "Please select an employee to delete")
            return
        
        # Get selected employee data
        item = self.tree.item(selection[0])
        staff_id = item['values'][0]
        employee_name = f"{item['values'][1]} {item['values'][2]}"
        
        # Confirm deletion
        result = tkinter.messagebox.askyesno("HOSPITAL DATABASE SYSTEM", 
                                           f"Are you sure you want to delete employee {employee_name}?")
        if result:
            try:
                if self.backend.delete_employee(staff_id):
                    tkinter.messagebox.showinfo("HOSPITAL DATABASE SYSTEM", "Employee deleted successfully")
                    self.refresh_data()
                else:
                    tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Failed to delete employee")
            except Exception as e:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", f"Error: {str(e)}")
    
    def close_window(self):
        """Close the global search window"""
        self.master.destroy()

#CLASS FOR EDIT EMPLOYEE WINDOW
class EditEmployeeWindow:
    def __init__(self, master, staff_id, backend, refresh_callback):
        self.master = master
        self.staff_id = staff_id
        self.backend = backend
        self.refresh_callback = refresh_callback
        
        self.master.title("EDIT EMPLOYEE")
        self.master.geometry("800x600+0+0")
        self.master.config(bg="#C0C0C0")
        self.frame = Frame(self.master, bg="#C0C0C0")
        self.frame.pack()
        
        # Get employee data
        self.employee = self.backend.get_employee(staff_id)
        if not self.employee:
            tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Employee not found")
            self.master.destroy()
            return
        
        # Create form variables
        self.emp_first_name = StringVar(value=self.employee[1])
        self.emp_last_name = StringVar(value=self.employee[2])
        self.emp_email = StringVar(value=self.employee[3])
        self.emp_phone = StringVar(value=self.employee[4])
        self.emp_specialization = StringVar(value=self.employee[5])
        self.emp_dept_id = IntVar(value=self.employee[6])
        self.emp_license_number = StringVar(value=self.employee[7] or "")
        self.emp_salary = StringVar(value=str(self.employee[8]))
        
        # Title
        self.lblTitle = Label(self.frame, text="EDIT EMPLOYEE", font="Arial 16 bold", bg="#C0C0C0", fg="#000080")
        self.lblTitle.grid(row=0, column=0, columnspan=2, pady=20)
        
        # Form frame
        self.form_frame = Frame(self.frame, bg="#C0C0C0")
        self.form_frame.grid(row=1, column=0, padx=20, pady=10)
        
        # Form fields
        row = 0
        Label(self.form_frame, text="STAFF ID:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Label(self.form_frame, text=staff_id, font="Arial 11", bg="#C0C0C0").grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="FIRST NAME:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.emp_first_name, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="LAST NAME:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.emp_last_name, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="EMAIL:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.emp_email, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="PHONE:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.emp_phone, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="SPECIALIZATION:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.emp_specialization, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="DEPARTMENT ID:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.emp_dept_id, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="SALARY:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.emp_salary, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="LICENSE NUMBER:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.emp_license_number, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        
        # Buttons
        self.button_frame = Frame(self.frame, bg="#C0C0C0")
        self.button_frame.grid(row=2, column=0, pady=20)
        
        Button(self.button_frame, text="SAVE", width=15, font="Arial 11 bold", 
               bg="#C0C0C0", relief="raised", bd=2, command=self.save_changes).pack(side=LEFT, padx=5)
        Button(self.button_frame, text="CANCEL", width=15, font="Arial 11 bold", 
               bg="#C0C0C0", relief="raised", bd=2, command=self.master.destroy).pack(side=LEFT, padx=5)
    
    def save_changes(self):
        """Save the changes to the employee"""
        try:
            # Validate email format
            email = self.emp_email.get().strip()
            if '@' not in email or '.' not in email:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Invalid email format")
                return
            
            # Validate phone number (allow digits, spaces, dashes, parentheses)
            phone = self.emp_phone.get().strip()
            phone_digits = ''.join(c for c in phone if c.isdigit())
            if len(phone_digits) < 7:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Phone number must have at least 7 digits")
                return
            
            update_data = {
                'first_name': self.emp_first_name.get().strip(),
                'last_name': self.emp_last_name.get().strip(),
                'email': email,
                'phone': phone_digits,  # Store only digits
                'specialization': self.emp_specialization.get().strip(),
                'dept_id': self.emp_dept_id.get(),
                'salary': float(self.emp_salary.get().strip()),
                'license_number': self.emp_license_number.get().strip() or None
            }
            
            if self.backend.update_employee(self.staff_id, update_data):
                tkinter.messagebox.showinfo("HOSPITAL DATABASE SYSTEM", "Employee updated successfully")
                self.refresh_callback()
                self.master.destroy()
            else:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Failed to update employee")
                
        except Exception as e:
            tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", f"Error: {str(e)}")

